package com.cpkso.yzx.repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;

import com.cpkso.yzx.domain.Msg;
import com.cpkso.yzx.dto.MsgQuery;

import runze.util.base.HibernateDaoImp;
import runze.util.base.IDao;
import runze.util.base.Query;
import runze.util.base.SQLBean;

/**
 * @author wrzhxy@qq.com
 * @date 2017年11月9日
 */
@Repository
public class MsgRepository extends HibernateDaoImp<Msg> implements IDao<Msg> {
	private static final String READ = "update Msg set read=1";
	/**
	 * 设置全部已读
	 * @return
	 */
	public int read() {
		Session session = getSessionFactory().getCurrentSession();
		session.createQuery(READ).executeUpdate();
		return 1;
	}
	
	@Override
	public List<Msg> find(Query query) {
		SQLBean sqlbean = query(query);
		return super.find(query, sqlbean.getHql(), sqlbean.getParams());
	}
	@Override
	public long getTotal(Query query) {
		SQLBean sqlbean = query(query);
		return super.getTotal(sqlbean.getHql(), sqlbean.getParams());
	}
	private SQLBean query(Query query) {
		String hql = "from Msg where 1=1";
		List<Object> objs = new ArrayList<>();
		
		MsgQuery mq = (MsgQuery) query;
		if (mq == null) mq = new MsgQuery();
		Date beginTime = mq.getBeginTime();
		if (beginTime != null) {
			hql += " and curtime>?";
			objs.add(beginTime);
		}
		Date endTime = mq.getEndTime();
		if (endTime != null) {
			hql += " and curtime<?";
			objs.add(endTime);
		}
		hql += " order by id desc";
		
		Object[] params = super.listToParams(objs);
		
		return new SQLBean(hql, params);
	}
}
